package com.tanzeer.deliverytracker.utility;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.TableRow;
import android.widget.Toast;

import com.tanzeer.deliverytracker.dbhelper.RelsellDBOpenHelper;
import com.tanzeer.deliverytracker.models.RowItem;

public class TrackerServiceClass extends Service {

	
    private SharedPreferences mSharedpreferences;
    public static final String TRACKPREFERENCES = "TrackingPrefs" ;
	public static final int GOT_DATA_FOR_TRACK_NO = 1007;
	private ArrayList<RowItem> mRefreshList;
	private String caller;
	private boolean bulkCaller;
	private String trackId;
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case GOT_DATA_FOR_TRACK_NO:
				HashMap<String, String> localHm = (HashMap<String, String>) msg.obj;
				Set<String> kSet = localHm.keySet();
				String str = null;
				for(String key : kSet){
					str = localHm.get(key);
					HashMap<String, String> trackIdAndStatus = new HashMap<String, String>();
					if (str != null && !str.contains("Item Summary")) {
						parseHtmlForItemSummary(str, trackIdAndStatus,key);
						int count = countRowsForActivitySummary(str);
						RelsellDBOpenHelper rHelper = new RelsellDBOpenHelper(getApplicationContext());
						rHelper.updateItemDataForTrackNo(null, trackIdAndStatus.get("status"), trackIdAndStatus.get("destination"), trackIdAndStatus.get("origin"), trackIdAndStatus.get("trackno"));
						for (int i = 0; i < count; i++) {
							String returnedRowData = parseHtmlForRow(str, i);
							String localDateTimeStr = extractString(returnedRowData, "<td>", "</td>");
							returnedRowData = skipTag(returnedRowData, "<td>", "</td>");

							String activityStr = extractString(returnedRowData, "<td>", "</td>");
							
							returnedRowData = skipTag(returnedRowData, "<td>", "</td>");

							String locationStr = extractString(returnedRowData, "<td>", "</td>");
							
							returnedRowData = skipTag(returnedRowData, "<td>", "</td>");

							String remarksStr = extractString(returnedRowData, "<td>", "</td>");
							
							rHelper.saveActivitySummaryForItem(trackIdAndStatus.get("trackingid"),trackIdAndStatus.get("trackno"), localDateTimeStr, activityStr, locationStr, remarksStr);
						}
						String returnedRowData = null;
						if (count == 0) {
		                	returnedRowData = parseHtmlForInfoInActivityTable(str);
		                	
		                }
						ApplicationVars.getInstance()
								.updateDeliveryListUIAfterManualRefresh(
										trackIdAndStatus,returnedRowData);
					} else {
                         
					}
					break;
				}

				break;
			}
		}
		
	};
	
	
	private String parseHtmlForInfoInActivityTable(String str) {
		int resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">");
		str = str.substring(resultsPanelDivStart);
		resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">")
				+ "<div id=\"resultsPanel\">".length(); // refreshing values
		int resultsPanelDivEnd = str.indexOf("</div>");
		str = str.substring(resultsPanelDivStart, resultsPanelDivEnd);
		str = skipTag(str, "<table>", "</table>");
		str = skipTag(str, "<table>", "</table>");
		str = extractString(str, "<p>", "</p>");	
		return str;
	}
	
	private int countRowsForActivitySummary(String str) {
		int res = 0;
		int resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">");
		str = str.substring(resultsPanelDivStart);
		resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">")
				+ "<div id=\"resultsPanel\">".length(); // refreshing values
		int resultsPanelDivEnd = str.indexOf("</div>");
		str = str.substring(resultsPanelDivStart, resultsPanelDivEnd);
		str = skipTag(str, "<table>", "</table>");
		str = extractString(str, "<table>", "</table>");
		str = skipTag(str, "<tr>", "</tr>"); // first heading row is skipped
		while ((str = skipTag(str, "<tr>", "</tr>")) != null) {
			res++;
		}
		return res;
	}
	
	private String parseHtmlForRow(String str, int rowNotoExtract) {

		int resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">");
		str = str.substring(resultsPanelDivStart);
		resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">")
				+ "<div id=\"resultsPanel\">".length(); // refreshing values
		int resultsPanelDivEnd = str.indexOf("</div>");
		str = str.substring(resultsPanelDivStart, resultsPanelDivEnd);
		str = skipTag(str, "<table>", "</table>");
		str = extractString(str, "<table>", "</table>");
		str = skipTag(str, "<tr>", "</tr>"); // skip heading
		if (rowNotoExtract == 0) {
			str = extractString(str, "<tr>", "</tr>");
		}
		if (rowNotoExtract == 1) {
			str = skipTag(str, "<tr>", "</tr>");
			str = extractString(str, "<tr>", "</tr>");
		} else if (rowNotoExtract == 2) {
			str = skipTag(str, "<tr>", "</tr>");
			str = skipTag(str, "<tr>", "</tr>");
			str = extractString(str, "<tr>", "</tr>");
		} else if (rowNotoExtract == 3) {
			str = skipTag(str, "<tr>", "</tr>");
			str = skipTag(str, "<tr>", "</tr>");
			str = skipTag(str, "<tr>", "</tr>");
			str = extractString(str, "<tr>", "</tr>");
		}
		return str;

	}
	
	private void parseHtmlForItemSummary(String str,HashMap <String,String> trackIdAndStatus,String trackingId) {
		int resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">");
		str = str.substring(resultsPanelDivStart);
		resultsPanelDivStart = str.indexOf("<div id=\"resultsPanel\">")
				+ "<div id=\"resultsPanel\">".length(); // refreshing values
		int resultsPanelDivEnd = str.indexOf("</div>");
		str = str.substring(resultsPanelDivStart, resultsPanelDivEnd);
		str = extractString(str, "<table>", "</table>");
		str = skipTag(str, "<tr>", "</tr>");
		String trackingNo = extractString(str, "<td>", "</td>");
		str = skipTag(str, "<td>", "</td>");
		String origin = extractString(str, "<td>", "</td>");
		str = skipTag(str, "<td>", "</td>");
		String dest = extractString(str, "<td>", "</td>");
		str = skipTag(str, "<td>", "</td>");
		String status = extractString(str, "<td bgcolor=\"#80FF80\">",
				"</td>");
        String completed = null;
		if (status.equalsIgnoreCase("Not Delivered")) {
			status = "Status: "+status;
		} else {
			completed = "0";
		}
		trackIdAndStatus.put("trackingid",trackingId);
		trackIdAndStatus.put("trackno",trackingNo);
		trackIdAndStatus.put("origin",origin);
		trackIdAndStatus.put("destination",dest);
		trackIdAndStatus.put("status",status);
	}
	
	public String extractString(String hayStack, String startTag,
			String endTag) {
		
		String extractedString = null;
		try {
		int indexEndTagStart = hayStack.indexOf(endTag);
		startTag = startTag.substring(0, startTag.lastIndexOf(">"));
		int indexStartTagStart = hayStack.indexOf(startTag);

		int indexStartTagEnd = hayStack.indexOf('>', indexStartTagStart);
		indexStartTagEnd++;
		extractedString = hayStack.substring(indexStartTagEnd,
				indexEndTagStart);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return extractedString;
	}

	public String skipTag(String hayStack, String startTag, String endTag) {
		String resultant = null;
		try {
			int endIndex = hayStack.indexOf(endTag);
			resultant = hayStack.substring(endIndex + endTag.length());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultant;
	}
	
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		System.out.println("service start");
		mSharedpreferences = getSharedPreferences(TRACKPREFERENCES,
				Context.MODE_PRIVATE);

		if (mSharedpreferences.contains("caller")) {
			caller = mSharedpreferences.getString("caller", null);
		}
		if (caller != null && caller.equalsIgnoreCase("0")) {
			String type = intent.getStringExtra("type");
			String categoryName = intent.getStringExtra("categoryName");
			
			bulkCaller = mSharedpreferences.getBoolean("bulkcaller",false);
		    if(bulkCaller) {
			mRefreshList = ApplicationVars.getInstance()
					.getTrackNoListToRefresh(this, type, categoryName,bulkCaller);
		    } else {
		    	trackId =  mSharedpreferences.getString("idForTrack","No value");
		    	if (mRefreshList != null ){
		    		mRefreshList.clear();
		    	}
		    	mRefreshList = ApplicationVars.getInstance().getSingleTrackNoList(this,trackId);
		    }
			
			
		} else if (caller != null && caller.equalsIgnoreCase("1")) {
			mRefreshList = ApplicationVars.getInstance()
					.getTrackNoListToRefresh(this);
		}
		if (mRefreshList != null) {
			for (RowItem rItem : mRefreshList) {
				new SendTask(this, rItem).execute();
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}
	


	@Override
	public void onDestroy() {
		Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
		super.onDestroy();
	}
	
	public class SendTask extends AsyncTask<Void, Void, String> {

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(result != null){
				Message msg = new Message();
				msg.what = GOT_DATA_FOR_TRACK_NO;
				HashMap<String,String> localHm = new HashMap<String, String>();
				localHm.put(rItem.itemSummary._id,result);
				msg.obj = localHm;
				mHandler.sendMessage(msg);
			}
		}

		private Context mContext;
		private RowItem rItem;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		public SendTask(Context context,RowItem rItem) {
			this.mContext = context;
			this.rItem = rItem;
		}

		@Override
		protected String doInBackground(Void... params) {
			try {

				
				String searchEditBoxValue = rItem.itemSummary.trackno;
				String encodedMatter = URLEncoder.encode(searchEditBoxValue, "utf-8");

				HttpClient http = new DefaultHttpClient();

				HttpGet get = new HttpGet(
						"http://globaltracktrace.ptc.post/gtt.web/Search.aspx?__LASTFOCUS=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUKMTc3NjQ4MjIxM2Rke75CFXa4GKxBOHumSyRDu081aGM%3D&__EVENTVALIDATION=%2FwEWAwKyj9zfDgKj5vrWDAKln%2FPuCgvWD%2FM%2FMsU5fSmm%2F1vVYpTAdczC&txtItemID="
								+ encodedMatter + "&btnSearch=Search");

				HttpResponse response = http.execute(get);
				String responseStr = new BasicResponseHandler()
						.handleResponse(response);
				return responseStr;
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
			
		}
	}
	
}
